package com.wyw.zklock.learning.controller;

import com.wyw.zklock.learning.lock.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/3/29 10:13
 * Update History:
 * Author        Time            Content
 */
@RestController
@Slf4j
public class DemoController {

    @Autowired
    private CuratorFramework client;

    @RequestMapping("zkLock")
    public String zkLock(){
        log.info("进入了方法！");
        try (ZkLock zkLock = new ZkLock("wyw:2185","order")){
            if (zkLock.getLock()) {
                log.info("进入了锁！！");
                Thread.sleep(15000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成");
        return "方法执行完成";
    }

    @RequestMapping("/curatorLock")
    public String curatorLock(){
        log.info("进入curatorLock方法");
        InterProcessMutex lock = new InterProcessMutex(client, "/order");
        try {
            if(lock.acquire(30, TimeUnit.SECONDS)){
                log.info("获得了锁！！");
                Thread.sleep(10000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                log.info("我释放了锁！！");
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("方法执行完成！");
        return "方法执行完成！";
    }
}
